package me.seu.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 延时消息
 *
 * @author liangfeihu
 * @since 2020/4/17 14:38
 */
@Slf4j
@RestController
@RequestMapping("/delay")
public class DelayMsgController {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/send")
    public ResponseEntity sendDelayMsg() {
        for (int i = 1; i < 4; i++) {
            try {
                String sendTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
                // 构造消息体
                Message msg = MessageBuilder.withPayload("rocketMQTemplate delay message " + i)
                        .setHeader("SEND_TIME", sendTime).build();
                SendResult sendResult = rocketMQTemplate.syncSend("delay-topic", msg, 300000L, i);
                log.info("### rocketMQTemplate send delay msg body=[{}], sendResult={}", msg.getPayload(), sendResult.getSendStatus());

                Thread.sleep(10);
            } catch (Exception e) {
                log.error("### rocketMQTemplate send delay msg error: ", e);
            }
        }
        return ResponseEntity.ok("send delay message success");
    }

}
